import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';

@Injectable()
export class AuthService {
  constructor(private jwt: JwtService, private usersService: UsersService) {}

  /**
   * 验证用户凭据，返回用户信息（不包含密码）
   */ 
  async validateUser(username: string, password: string) {
    const user = await this.usersService.findByUsername(username);
    if (!user || user.password !== password) {
      throw new UnauthorizedException('Invalid credentials');
    }
    const { password: _pwd, ...result } = user;
    return result;
  }

  /**
   * 登录路由，验证用户凭据并返回 JWT 令牌
   */ 
  async login(user: { id: number; username: string; roles: string[] }) {
    const payload = { sub: user.id, username: user.username, roles: user.roles };
    return {
      access_token: await this.jwt.signAsync(payload), // 返回 JWT 令牌
    };
  }
}